import requests
import json

from utils.log_util import logger
from utils.read import base_data

api_mini_url = base_data.read_ini()['host']['api_mini_url']


class RestClient:
    def __init__(self):
        self.api_mini_url = api_mini_url
        self.session = requests.Session()

    def get(self, url, **kwargs):
        return self.request(url, "GET", **kwargs)

    def post(self, url, **kwargs):
        return self.request(url, "POST", **kwargs)

    def put(self, url, **kwargs):
        return self.request(url, "PUT", **kwargs)

    def delete(self, url, **kwargs):
        return self.request(url, "DELETE", **kwargs)

    def request(self, url, method, **kwargs):
        self.logs(url, method, **kwargs)
        if method == "GET":
            return self.session.get(self.api_mini_url + url, **kwargs)
        if method == "POST":
            # urls = self.api_mini_url + url
            # datas = {
            #     "mobile": 17684548457
            # }
            # a = requests.post(urls, datas)
            result = self.session.post(self.api_mini_url + url, **kwargs)
            return result
        if method == "PUT":
            return self.session.put(self.api_mini_url + url, **kwargs)
        if method == "DELETE":
            return self.session.delete(self.api_mini_url + url, **kwargs)

    def logs(self, url, method, **kwargs):
        data = dict(**kwargs).get("data")
        params = dict(**kwargs).get("params")
        json_data = dict(**kwargs).get("json")
        logger.info("接口请求地址》》》{}".format(self.api_mini_url + url))
        logger.info("接口请求方法》》》{}".format(method))
        if data is not None:
            logger.info("接口请求参数》》》\n{}".format(json.dumps(data, indent=4, ensure_ascii=False)))
        if json_data is not None:
            logger.info("接口请求参数》》》\n{}".format(json.dumps(json_data, indent=4, ensure_ascii=False)))
        if params is not None:
            logger.info("接口请求数据》》》\n{}".format(json.dumps(params, indent=4, ensure_ascii=False)))

